﻿dynamic class Autho {
	private static var $Autho_ins:Autho;
	/* Check Parent's Permission*/
	public static var CheckParentAuthos:Boolean = true;
	/*if the Function's permission isn't set , how to do*/
	public static var SetPermissionAsNoAuthoRecord = true;
	
	private var $authos:Object;
	public function Autho() {
		initvars();
	}
	
	private function initvars():Void{
		this.$authos = new Object();
	}
	
	static public function get Autho_ins():Autho { 
		if ($Autho_ins == undefined) {
			$Autho_ins = new Autho;
		}
		return $Autho_ins; 
	}
	
	public function Permission(functionCode:String):Boolean {
		var fc:Number = Number(functionCode);
		//trace(fc.toString(16));
		if (fc.toString() == "NaN") {
			this.esay("Error funCode[" + functionCode + "] when check Permission.");
			return null;
		}
		if(CheckParentAuthos){
			if (checkParentPermission(fc)) {
				if (this.$authos[fc] == undefined) {
					return SetPermissionAsNoAuthoRecord;
				}else {
					return this.$authos[fc].at;
				}
			}else {
				return false;
			}
		}else {
			if (this.$authos[fc] == undefined) {
				return SetPermissionAsNoAuthoRecord;
			}else {
				return this.$authos[fc].at;
			}
		}
	}
	private function checkParentPermission(functionCode:Number):Boolean {
		if (functionCode == 0) return SetPermissionAsNoAuthoRecord;
		var fch:Number = 0;
		var i:Number=0
		while (functionCode > 0xff) {
			var fc:Number = functionCode & 0xff;
			functionCode = functionCode >> 8;
			fch = fch | (fc << (8*i));
			//trace(fch.toString(16));
			if (this.$authos[fch] != undefined) {
				if (this.$authos[fch].at == false) {
					return false;
				}
			}else {
				if (!SetPermissionAsNoAuthoRecord) {
					return false;
				}
			}
			i++;
		}
		return true;
	}
	public function AddAuthoTable(authos:Array, funcodename:String, authoname:String) {
		if (funcodename == undefined) {
			funcodename = "funcode";
		}
		if (authoname == undefined) {
			authoname = "autho";
		}
		for (var i = 0; i < authos.length; i++) {
			this.AddAutho(authos[i][funcodename], authos[i][authoname]);
		}
	}
	public function AddAutho(functionCode:String, autho:Boolean):Void {
		var fc:Number = Number(functionCode);
		if (fc.toString() == "NaN") {
			this.esay("Add Autho Error of error funCode[" + functionCode + "].");
			return;
		}
		if (autho == undefined) {
			autho = false;
		}
		msay("Add Autho:["+functionCode+"] = "+autho);
		this.$authos[fc] = { fc:functionCode, at:autho };
	}
	public function DelAutho(functionCode:String) {
		delete this.$authos[functionCode];
	}
	
	private function msay(o) {
		//CRM_Index.index_ins.say.msay(o);
		trace("AUTHO: " + o.toString());
	}
	private function wsay(o) {
		//CRM_Index.index_ins.say.esay(o);
		trace("AUTHO:**error** " + o.toString());
	}
	private function wsay(o) {
		//CRM_Index.index_ins.say.esay(o);
		trace("AUTHO:**wronnig** " + o.toString());
	}
}